package com.hexiang.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hexiang.dao.cluster.CityDao;
import com.hexiang.dao.master.UserDao;
import com.hexiang.domain.City;
import com.hexiang.domain.User;
import com.hexiang.service.UserService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户业务实现层
 */
@Service
public class UserServiceImpl implements UserService {

    /**
     * 主数据源
     */
    @Autowired
    private UserDao userDao;

    /**
     * 从数据源
     */
    @Autowired
    private CityDao cityDao;

    @Override
    public User findByName(String userName) {
        User user = userDao.findByName(userName);
        City city = cityDao.findById(user.getCity().getId());
        user.setCity(city);
        return user;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveUser(User user) {
        City cityResult = cityDao.findByName(user.getCity().getCityName());

        if (null == cityResult) {
            cityDao.saveCity(user.getCity());
        }
        user.setCity(cityResult);
        return userDao.saveUser(user, user.getCity());
    }
}
